package com.blue.http.util;

import java.io.File;
import java.net.InetSocketAddress;

import javax.activation.MimetypesFileTypeMap;

import com.alibaba.fastjson.JSONObject;
import com.blue.http.config.ErrorConfig;
import com.blue.http.message.HttpResponse;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;
import io.netty.util.Version;

/**
 * Http服务器工具类
 * 
 * @author zhengj
 * @since 1.0 2016年9月4日
 */
public class HttpServerUtil
{
	private HttpServerUtil()
	{
	}
	
	public static void sendJson(ChannelHandlerContext ctx, FullHttpRequest request, HttpResponse message)
	{
		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
		
		/*boolean close = HttpUtil.isKeepAlive(request) || request.protocolVersion().equals(HttpVersion.HTTP_1_0);
		HttpUtil.setKeepAlive(response, close);*/
		
		String result = null;
		if (message.getCode() == ErrorConfig.SUCCESS)
		{
			result = message.getResult();
		}
		else
		{
			JSONObject object = new JSONObject();
			object.put("code", message.getCode());
			object.put("msg", message.getMsg());
			object.put("extmsg", message.getExtmsg());
			result = object.toJSONString();
		}
		if (result == null || result.isEmpty())
		{
			JSONObject object = new JSONObject();
			object.put("code", ErrorConfig.SUCCESS);
			object.put("msg", ErrorConfig.getInstance().get(ErrorConfig.SUCCESS));
			result = object.toJSONString();
		}
		
		ByteBuf buf = Unpooled.copiedBuffer(result, CharsetUtil.UTF_8);
		response.content().writeBytes(buf);
		buf.release();
		ctx.writeAndFlush(response);
		/*ChannelFuture channelFuture = ctx.writeAndFlush(response);
		if (close)
		{
			channelFuture.addListener(ChannelFutureListener.CLOSE);
		}*/
	}
	
	public static void sendRedirect(ChannelHandlerContext ctx, String uri)
	{
		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND);
		HttpHeaders headers = response.headers();
		headers.set(HttpHeaderNames.LOCATION, uri);
		ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
	}
	
	public static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status)
	{
		String ver = "4.1.4 Final";
		Version version = Version.identify().get("netty-common");
		if (version != null)
			ver = version.artifactVersion();
		
		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
		HttpHeaders headers = response.headers();
		headers.set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
		
		StringBuilder sb = new StringBuilder(256);
		sb.append("<!doctype html>\r\n<html>\r\n<head>\r\n<meta charset=\"UTF-8\"/>\r\n<title>Error</title>\r\n</head>\r\n<body>\r\n");
		sb.append("<center><h1>").append(status.toString()).append("</h1></center><hr/><h4>Netty");
		sb.append(ver).append("</h4>");		
		sb.append("</body>\r\n</html>\r\n");
		ByteBuf buf = Unpooled.copiedBuffer(sb, CharsetUtil.UTF_8);
		response.content().writeBytes(buf);
		buf.release();
		ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
	}
	
	public static void setContentType(io.netty.handler.codec.http.HttpResponse response, File file)
	{
		MimetypesFileTypeMap mimeTypeMap = new MimetypesFileTypeMap();
		HttpHeaders headers = response.headers();
		headers.set(HttpHeaderNames.CONTENT_TYPE, mimeTypeMap.getContentType(file));
	}
	
	public static String getIp(HttpHeaders headers, Channel channel)
	{
		String ip = headers.get("x-forwarded-for");
		if (ip == null || ip.isEmpty() || ip.equalsIgnoreCase("unknown"))
		{
			ip = headers.get("Proxy-Client-IP");
		}
		if (ip == null || ip.isEmpty() || ip.equalsIgnoreCase("unknown"))
		{
			ip = headers.get("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.isEmpty() || ip.equalsIgnoreCase("unknown"))
		{
			InetSocketAddress address = (InetSocketAddress)channel.remoteAddress();
			ip = address.getAddress().getHostAddress();
		}
		return ip;
	}
	
}
